package ljl.codetop2;

import commons.ListNode;

public class _24_swap_pairs {

    /**
     * 这不 k 个一组反转链表吗我去？
     */
    static class a {
        public ListNode swapPairs(ListNode head) {
            ListNode dm = new ListNode(0, head);
            ListNode prev = dm;
            while (head != null) {
                ListNode start = head;
                ListNode tail = head.next;
                if (tail == null) break;
                ListNode next = tail.next;
                prev.next = reverse(start, next);
                prev = start;
                head = next;
            }
            return dm.next;
        }
        ListNode reverse(ListNode head, ListNode next) {
            ListNode tail = head.next;
            tail.next = head;
            head.next = next;
            return tail;
        }
    }

    /**
     * 我还以为我很聪明，看了官方题解：我是弱智
     *
     * 很优雅
     */
    static class off1 {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = head.next;
            head.next = swapPairs(newHead.next);
            newHead.next = head;
            return newHead;
        }
    }

    static class copy_off1 {
        // head head1 head2
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode res = head.next;
            head.next = swapPairs(res.next);
            res.next = head;
            return res;
        }
    }

    /**
     * k 个一组翻转链表把我害了，简单解法反而没想到
     */
    static class off2 {
        public ListNode swapPairs(ListNode head) {
            ListNode dummyHead = new ListNode(0, head);
            ListNode prev = dummyHead;
            while (prev.next != null && prev.next.next != null) {
                ListNode node1 = prev.next;
                ListNode node2 = prev.next.next;
                prev.next = node2;
                node1.next = node2.next;
                node2.next = node1;
                prev = node1;
            }
            return dummyHead.next;
        }
    }

    static class copy_off2 {
        public ListNode swapPairs(ListNode head) {
            ListNode dm = new ListNode(0, head);
            ListNode prev = dm;
            while (prev.next != null && prev.next.next != null) {
                ListNode n1 = prev.next, n2 = n1.next;
                prev.next = n2;
                n1.next = n2.next;
                n2.next = n1;
                prev = n1;
            }
            return dm.next;
        }
    }
}
